package com.tender.integration.websocket;

import com.tender.integration.websocket.handler.DefaultWebSocketHandler;
import com.tender.integration.websocket.interceptor.WebSocketInterceptor;
import com.tender.integration.websocket.service.WebSocketService;
import com.tender.integration.websocket.service.impl.WebSocketServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

/**
 * websocket 集群解决方案：推荐方案二
 * https://www.cnblogs.com/shiyuelp/p/17264482.html
 *
 * 需要配置注解：@EnableWebSocket 否则，客户端的 WebSocket 连接不上 服务端
 *
 */
@Configuration
public class WebSocketConfiguration implements WebSocketConfigurer {

    /**
     * SpringBoot 封装的 不需要这个Bean
     * 初始化Bean，它会自动注册使用了 @ServerEndpoint 注解声明的 WebSocket endpoint
     */
//    @Bean
//    public ServerEndpointExporter serverEndpointExporter() {
//        return new ServerEndpointExporter();
//    }

    @Bean
    public WebSocketService webSocketService() {
        return new WebSocketServiceImpl();
    }

    @Bean
    public WebSocketHandler webSocketHandler() {
        return new DefaultWebSocketHandler();
    }

    @Bean
    public WebSocketInterceptor webSocketInterceptor() {
        return new WebSocketInterceptor ();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 链接方式如下 ws://10.220.5.226:8086/ws/msg?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwNzYyZjhlYS1jNDE4LTQ2ZGUtOGZkNi1kMjVkYTk1Mzk2NmYiLCJ1c2VyX25hbWUiOiJsdWN5IiwiaWF0IjoxNzI0OTAxMTUxLCJhZ2UiOjEwLCJqdGkiOiI4ODg4ODg4OCJ9.sGv6rglWbNsaAuZvcqsD7yy_OANVgYe7ZNGOPQ_j4Uk
        // 如果你设置了SpringBoot的 contentPath 那就需要在:9085端口后面 加上contentPath 的值，再拼接上  ws/msg?token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIwNzYyZjhlYS1jNDE4LTQ2ZGUtOGZkNi1kMjVkYTk1Mzk2NmYiLCJ1c2VyX25hbWUiOiJsdWN5IiwiaWF0IjoxNzI0OTAxMTUxLCJhZ2UiOjEwLCJqdGkiOiI4ODg4ODg4OCJ9.sGv6rglWbNsaAuZvcqsD7yy_OANVgYe7ZNGOPQ_j4Uk
        registry.addHandler(webSocketHandler(), "/ws/msg")
                .addInterceptors(webSocketInterceptor())
                .setAllowedOrigins("*");
    }

}
